<template>
  <div class="create-question-wrapper">
    <Button
      type="primary"
      size="small"
      @click="addObjectiveQuestion($event, 'add')"
      class="md-add-jh"
      >创建题目</Button
    >
    <!-- <Tooltip max-width="200" content="多选题大于4个选项的题目请手动录入" class="ml10">
                <Upload
                    ref="upload"
                    :action="uploadAction"
                    :show-upload-list="false"
                    :format="['xlsx']"
                    :on-format-error="handleFormatError"
                    :on-success="getImageUrl"
                    @on-error="uploadError"
                    :on-progress="handleProgress"
                    :before-upload="handleBeforeUpload"
                    :headers="uploadHeader"
                >
                    <Button style="height: 32px;" type="primary" :disabled="uploadList.length > 0">
                        <div v-if="uploadList.length == 0">
                            <Icon type="ios-cloud-upload-outline"></Icon>
                            <span>导入客观题</span>
                        </div>
                        <div class="demo-upload-list" v-for="item in uploadList">
                            <Progress
                                v-if="item.showProgress"
                                :percent="item.percentage"
                                hide-info
                                style="width:100px"
                            ></Progress>
                        </div>
                    </Button>
                </Upload>
            </Tooltip>
            <Button class="ml10" type="primary" icon="ios-download-outline"
                ><a
                    href="../../api/new-paper/objective/question/excel-template"
                    download=""
                    class="downloadUrl"
                    >导出导入客观题模板</a
                ></Button 
            >-->
    <Modal
      v-model="addObjectiveQuestionModal.show"
      :title="addObjectiveQuestionModal.title"
      :loading="addObjectiveQuestionModal.loading"
      :mask-closable="false"
      @on-ok="saveObjectQuestion('objectiveQuestionformValidate')"
      @on-cancel="resetField('objectiveQuestionformValidate')"
      width="600px"
    >
      <Form
        ref="objectiveQuestionformValidate"
        :model="objectiveQuestionformValidate"
        :rules="ruleobjectiveQuestionValidate"
        :label-width="120"
      >
        <FormItem label="题目类型" prop="modeCode">
          <Select filterable
            v-model="objectiveQuestionformValidate.modeCode"
            placeholder="请选择题目类型"
            @on-change="changeAnswerTxt"
            :disabled="questiontypeDisbaled"
          >
            <Option :value="1">单选</Option>
            <Option :value="2">多选</Option>
            <Option :value="3">判断</Option>
            <Option :value="4">填空</Option>
            <!--<Option :value="5">简答</Option>-->
          </Select>
        </FormItem>
        <FormItem label="名称" prop="description">
          <!-- <Input
                        v-model.trim="objectiveQuestionformValidate.description"
                        placeholder="题目名称长度为1-128个字符"
                        v-if="objectiveQuestionformValidate.modeCode != 4"
                    ></Input> -->
          <!-- <QuillEditorItem
            v-if="objectiveQuestionformValidate.modeCode != 4"
            :dataValue="objectiveQuestionformValidate.description"
            type="questionName"
            @editorChange="editorChange"
          /> -->
          <Input
            v-if="objectiveQuestionformValidate.modeCode != 4"
            v-model.trim="objectiveQuestionformValidate.description"
            placeholder="题目名称长度为1-1000个字符"
            type="textarea"
            :maxlength="1000"
            :rows="4"
          ></Input>
          <div v-else>
            <p
              id="quesContent"
              @input="changeContent"
              @blur="validAnswer('blur')"
              @paste="getIndexAndCurContent"
              placeholder="题目名称长度为1-1000个字符"
              class="ivu-input"
              :style="{
                background:
                  addObjectiveQuestionModal.title === '编辑客观题'
                    ? '#f3f3f3'
                    : '',
              }"
              :contenteditable="
                addObjectiveQuestionModal.title === '编辑客观题' ? false : true
              "
            ></p>
            <div v-if="!objectiveQuestionformValidate.id">
              <Button
                @click="insertHtmlAtCaret('')"
                type="primary"
                size="small"
                :disabled="disAddBlank"
                >插入填空区</Button
              >
              <WarningTip placement="right">
                <p>1、可在光标选中位置插入填空区</p>
                <p>
                  2、每个题目只能插入一个填空区，且填空区内容长度为为1-64个字符
                </p>
                <p>3、题目名称长度为1-1000个字符</p>
              </WarningTip>
              <!-- <p>
                                <small style="color:#f90"
                                    ><Icon
                                        type="ios-information-circle"
                                    />可在光标选中位置插入填空区</small
                                >
                            </p>
                            <p>
                                <small style="color:#f90"
                                    ><Icon
                                        type="ios-information-circle"
                                    />每个题目只能插入一个填空区,且填空区内容长度为为1-64个字符</small
                                >
                            </p>
                            <p>
                                <small style="color:#f90"
                                    ><Icon
                                        type="ios-information-circle"
                                    />题目名称长度为1-128个字符</small
                                >
                            </p> -->
              <p>
                <small style="color: #ed4014">{{ errorTip4 }}</small>
              </p>
            </div>
          </div>
        </FormItem>
        <FormItem label="知识点" prop="typeCode">
          <!-- <Select filterable
                        v-model="objectiveQuestionformValidate.typeCode"
                        placeholder="请选择知识点"
                        filterable
                    >
                        <Option
                            v-for="item in typeCodeObj"
                            :key="item.dictid"
                            :value="item.dictid"
                            :title="item.dictname"
                            >{{ item.dictname }}</Option
                        >
                    </Select> -->
          <Cascader
            :data="treeDirectionData"
            v-model="objectiveQuestionformValidate.typeCode"
            placeholder="请选择知识点"
            filterable
          ></Cascader>
        </FormItem>
        <FormItem label="题目难度" prop="difficulty">
          <Select filterable
            v-model="objectiveQuestionformValidate.difficulty"
            placeholder="请选择题目难度"
          >
            <Option value="simple">简单</Option>
            <!--<Option  value="commonly">一般</Option>-->
            <Option value="medium">中等</Option>
            <Option value="hard">较难</Option>
          </Select>
        </FormItem>
        <!-- <FormItem label="可见范围" prop="visibility">
                    <RadioGroup v-model="objectiveQuestionformValidate.visibility">
                       
                        <Radio label="share">单位</Radio>
                        <Radio label="private">个人</Radio>
                    </RadioGroup>
                </FormItem> -->
        <span
          v-if="preQuestion && objectiveQuestionformValidate.modeCode != 4"
          class="questionclass"
        >
          <QuestionCard
            :question="objectiveQuestionformValidate"
          ></QuestionCard>
        </span>
        <span
          v-if="!preQuestion && objectiveQuestionformValidate.modeCode != 4"
        >
          <FormItem
            v-for="(item, index) in objectiveQuestionformValidate.answers"
            v-if="
              (objectiveQuestionformValidate.modeCode === 1 ||
                objectiveQuestionformValidate.modeCode === 2) &&
              item.status
            "
            :key="index"
            :label="'[' + filterIndex(index + 1) + ']'"
            :prop="'answers.' + index + '.description'"
            :rules="{
              required: true,
              message: '题目答案不能为空',
              trigger: 'change',
            }"
            class="answerForm"
          >
            <Row>
              <Col span="18">
                <Input
                  v-model.trim="item.description"
                  type="textarea"
                  :maxlength="200"
                  :rows="2"
                  placeholder="请输入题目答案"
                  style="margin-bottom: 12px"
                />
                <!-- <Input v-model.trim="item.explanation" type="text"  placeholder="请输入题目正确答案" />-->
              </Col>
              <Col span="4" offset="1">
                <span
                  v-if="
                    (objectiveQuestionformValidate.modeCode === 2 ||
                      objectiveQuestionformValidate.modeCode === 1) &&
                    objectiveQuestionformValidate.answers.length > 1
                  "
                  ><Button
                    @click="handleRemove(index)"
                    :disabled="
                      objectiveQuestionformValidate.answers.filter(
                        (item) => item.status
                      ).length === 1 ||
                      addObjectiveQuestionModal.title === '编辑客观题'
                    "
                    >删除</Button
                  ></span
                >
                <Radio
                  v-model="item.isRight"
                  v-if="objectiveQuestionformValidate.modeCode === 1"
                  @on-change="singleAnswer(index)"
                  :true-value="1"
                  :false-value="0"
                  :disabled="addObjectiveQuestionModal.title === '编辑客观题'"
                  >正确答案</Radio
                >
                <Checkbox
                  v-model="item.isRight"
                  v-if="objectiveQuestionformValidate.modeCode === 2"
                  :true-value="1"
                  :false-value="0"
                  :disabled="addObjectiveQuestionModal.title === '编辑客观题'"
                  >正确答案</Checkbox
                >
              </Col>
            </Row>
          </FormItem>
          <template v-if="objectiveQuestionformValidate.answers.length">
            <FormItem
              v-if="objectiveQuestionformValidate.modeCode === 3"
              label="题目答案"
              :prop="'answers[0].isRight'"
              :rules="{
                required: true,
                type: 'number',
                message: '题目答案不能为空',
                trigger: 'change',
              }"
            >
              <RadioGroup
                v-model="objectiveQuestionformValidate.answers[0].isRight"
              >
                <Radio
                  :label="1"
                  :disabled="addObjectiveQuestionModal.title === '编辑客观题'"
                  >正确</Radio
                >
                <Radio
                  :label="0"
                  :disabled="addObjectiveQuestionModal.title === '编辑客观题'"
                  >错误</Radio
                >
              </RadioGroup>
            </FormItem>
            <FormItem
              v-if="objectiveQuestionformValidate.modeCode === 5"
              label="题目答案"
              :prop="'answers[0].isRight'"
            >
              <Input
                v-model.trim="
                  objectiveQuestionformValidate.answers[0].description
                "
                type="textarea"
                :maxlength="200"
                :rows="2"
                placeholder="请输入题目答案"
                style="margin-bottom: 12px"
              />
            </FormItem>
          </template>
        </span>
        <FormItem
          style="margin-top: 0"
          v-if="
            objectiveQuestionformValidate.modeCode != 4 &&
            objectiveQuestionformValidate.modeCode != 5
          "
        >
          <Button
            type="primary"
            :disabled="
              disbledAdd || addObjectiveQuestionModal.title === '编辑客观题'
            "
            v-if="
              objectiveQuestionformValidate.modeCode === 2 ||
              objectiveQuestionformValidate.modeCode === 1
            "
            @click="addAnswers"
            >增加</Button
          >
          <Button
            type="primary"
            v-if="objectiveQuestionformValidate.modeCode"
            @click="showQuestion"
            >{{ preTxt }}</Button
          >
        </FormItem>
        <FormItem label="题目解析" prop="explanation">
          <Input
            v-model.trim="objectiveQuestionformValidate.explanation"
            type="textarea"
            :maxlength="1000"
            :rows="4"
            placeholder="解析信息"
          />
        </FormItem>
      </Form>
    </Modal>
    <!-- <ImportObjectiveFailModal
            :data="importResultData"
            :show="showFailModal"
            @on-close="showFailModal = false"
        ></ImportObjectiveFailModal> -->
  </div>
</template>
<script>
import usally from '@/mixin/usally';
import { allDirection } from '@/api/dict.js';
import {
    queryObjectiveList,
    delQuestion,
    createQuestion,
    modifyQuestion,
    getQuestionAndAnswer,
    exportQuestions
} from '@/api/question';
import { downloadObjectiveQuestion, downloadObjectiveQuestionTemplate } from '@/api/download';
import encryption from '@/libs/encryption.js';
import { debounce, downloadBlob } from '@/libs/utils';
// import ImportObjectiveFailModal from './components/import-objective-fail-modal.vue';
import QuillEditorItem from '@/components/quillEditor/index.vue';
import QuestionCard from '@/components/question-list/question-card.vue';
import { typeAndDirectionMixin } from '@/mixin/study';
export default {
    name: 'ObjectiveQuestion',
    components: { QuillEditorItem, QuestionCard },
    props: ['show'],
    mixins: [usally, typeAndDirectionMixin],
    data() {
        const typeCodelen = (rule, value, callback) => {
            if (value.length > 5) {
                callback(new Error('最多选择5个知识点'));
            }
            callback();
        };
        //	        const validateName = (rule, value, callback) => { //验证只能填入数字
        //		      	var reg = new RegExp("^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$");
        //		      	//验证警戒值
        //		      	if(value){
        //		      		if (!reg.test(value)) {
        //		      			callback(new Error('请输入中文、数字、字母、下划线、-'));
        //		      		}else{
        //		      			callback()
        //		      		}
        //		      	}else{
        //		      		callback()
        //		      	}
        //		    }
        const validateName = (rule, value, callback) => {
            //验证只能填入数字
            var reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
            //验证警戒值
            let _this = this;
            if (value) {
                if (_this.objectiveQuestionformValidate.modeCode == 4) {
                    callback();
                } else {
                    if (value.length < 1 || value.length > 1000) {
                        callback('题目名称长度为1-1000个字符');
                    } else {
                        callback();
                    }
                }
            } else {
                if (_this.objectiveQuestionformValidate.modeCode == 4) {
                    callback();
                } else {
                    callback('题目名称长度为1-1000个字符');
                }
            }
        };
        let September = sessionStorage.getItem('November');
        September = JSON.parse(encryption.SelfUseDecrypt(September));
        return {
            creatByMeModal: false,
            USER_ID: September.userId,
            USER_Name: September.nickname,
            isRootDesinger: September.isRootDesinger,
            // 页面设置
            fullHeight: document.documentElement.clientHeight,
            fullWidth: document.documentElement.clientWidth,
            setHei: 'auto',
            preQuestionDataObj: {},
            preQuestionModal: false,
            preQuestion: false,
            disbledAdd: false,
            preTxt: '预览',
            questiontypeDisbaled: false,
            objective: {
                questionname: '',
                page: 1,
                pageSize: 10,
                visibility: ''
            },
            objectiveCol: [
                {
                    type: 'selection',
                    width: 60
                },
                {
                    type:'link',
                    title: '名称',
                    key: 'description',
                    tooltip: true,
                    fun: this.preQuestionFn,
                    filter: (description) => {
                        return this.escape2Html(description);
                    }
                },
                {
                    title: '知识点',
                    key: 'typeCode',
                    tooltip: true,
                    filter: (typeCode) => {
                        return this.pointFilter(typeCode, this.typeCodeObj);
                    }
                },
                {
                    title: '难度',
                    key: 'difficulty',
                    align: 'left',
                    ellipsis: true,
                    filter: (difficulty) => {
                        return this.difficultyFilter(difficulty);
                    }
                },
                {
                    title: '可见范围',
                    key: 'visibility',
                    tooltip: true,
                    filter: (visible) => {
                        return this.setVisibility(visible).text;
                    },
                    setColor: (visible) => {
                        return this.setVisibility(visible).color;
                    }
                },
                {
                    title: '类型',
                    key: 'modeCode',
                    tooltip: true,
                    filter: (modeCode) => {
                        return this.questionMode(modeCode);
                    }
                },
                {
                    title: '设计者',
                    key: 'creatorName',
                    tooltip: true
                },
                // {
                //     title: '创建时间',
                //     key: 'created',
                //     tooltip: true
                // },
                {
                    title: '操作',
                    width: 140,
                    slot: 'action',
                    opList: [
                        {
                            txt: '修改',
                            disabled: this.setReBtnStatus,
                            fun: (data) => {
                                this.addObjectiveQuestion(data, 'modify');
                            }
                        },
                        {
                            txt: '删除',
                            type: 'delete',
                            tooltip: true,
                            title: '你确定要删除吗?',
                            disabled: this.setReBtnStatus,
                            fun: (data) => {
                                this.deleteQuestion(data.questionID);
                            }
                        }
                    ]
                }
            ],
            objectListTotal: 0,
            objectiveList: [],
            typeCodeObj: [],
            index: 1,
            addObjectiveQuestionModal: {
                show: false,
                title: '创建客观题',
                loading: true
            },
            questionAnswer: '题目答案(单选)',
            objectiveQuestionformValidate: {
                description: '',
                typeCode: [],
                application:'3',
                difficulty: '',
                modeCode: '',
                explanation: '',
                visibility: 'private',
                answers: [
                    {
                        index: 1,
                        answerId: '',
                        description: '',
                        enabled: 1,
                        explanation: '',
                        isRight: 0,
                        no: 0,
                        questionId: '',
                        status: 1
                    }
                ]
            },
            ruleobjectiveQuestionValidate: {
                description: [
                    { required: true, max: 1000, message: '题目名称长度为1-1000个字符', trigger: 'change' },
                    // { // 富文本
                    //     required: true,
                    //     message: '题目名称不能为空',
                    //     // validator: validateName,
                    //     trigger: 'change'
                    // }
                ],
                typeCode: [
                    {
                        type: 'array',
                        required: true,
                        min: 2,
                        message: '知识点不能为空',
                        trigger: 'change'
                    }
                ],
                difficulty: [
                    {
                        required: true,
                        message: '难度不能为空',
                        trigger: 'change'
                    }
                ],
                modeCode: [
                    {
                        required: true,
                        type: 'number',
                        message: '类型不能为空',
                        trigger: 'change'
                    }
                ],
                visibility: [
                    {
                        required: true,
                        message: '可见范围不能为空',
                        trigger: 'change'
                    }
                ]
            },
            initQuestionObj: {
                answers: [
                    {
                        answerId: '',
                        description: '',
                        enabled: 1,
                        explanation: '',
                        isRight: 0,
                        no: 0,
                        questionId: ''
                    }
                ],
                visibility: 'private',
                description: '',
                difficulty: '',
                enabled: 1,
                explanation: '',
                modeCode: 0,
                id: '',
                timer: 0,
                typeCode: []
            },
            // 显示
            showDataList: false,
            showDefImg: false,
            loading: false,
            quesAnswer4: '',
            errorTip4: '',
            disAddBlank: false,
            //导入客观题
            uploadAction: '/api/new-paper/objective/question/import?importSystem=designer',
            uploadHeader: {
                Authorization: localStorage.token,
                Accept: '*/*'
            },
            uploadList: [],
            uploaderror: false,
            filename: '',
            //导入结果
            importResultData: {},
            showFailModal: false,
            selectAllQuestion: false,
            selectQuestions: []
        };
    },
    computed: {},
    filters: {},
    methods: {
        editorChange(value) {
            this.objectiveQuestionformValidate.description = value;
        },
        filterIndex(val) {
            if (this.objectiveQuestionformValidate.modeCode === 3) {
                val = 0;
            }
            let str = '';
            switch (val) {
                case 1:
                    str = 'A';
                    break;
                case 2:
                    str = 'B';
                    break;
                case 3:
                    str = 'C';
                    break;
                case 4:
                    str = 'D';
                    break;
                case 5:
                    str = 'E';
                    break;
                case 6:
                    str = 'F';
                    break;
                case 7:
                    str = 'G';
                    break;
                case 8:
                    str = 'H';
                    break;
                case 9:
                    str = 'I';
                    break;
                case 10:
                    str = 'J';
                    break;
                case 11:
                    str = 'K';
                    break;
                case 12:
                    str = 'L';
                    break;
                default:
                    str = '';
                    break;
            }
            return str;
        },
        initFormData() {
            this.objectiveQuestionformValidate = {
                description: '',
                typeCode: [],
                difficulty: '',
                application:'3',
                modeCode: '',
                explanation: '',
                visibility: 'private',
                answers: [
                    {
                        index: 1,
                        answerId: '',
                        description: '',
                        enabled: 1,
                        explanation: '',
                        isRight: 0,
                        no: 1,
                        questionId: '',
                        status: 1
                    },
                    {
                        index: 2,
                        answerId: '',
                        description: '',
                        enabled: 1,
                        explanation: '',
                        isRight: 0,
                        no: 2,
                        questionId: '',
                        status: 1
                    },
                    {
                        index: 3,
                        answerId: '',
                        description: '',
                        enabled: 1,
                        explanation: '',
                        isRight: 0,
                        no: 3,
                        questionId: '',
                        status: 1
                    },
                    {
                        index: 4,
                        answerId: '',
                        description: '',
                        enabled: 1,
                        explanation: '',
                        isRight: 0,
                        no: 4,
                        questionId: '',
                        status: 1
                    }
                ]
            };
        },
        searchCreatedByMe(val) {
            this.objective.page = 1;

            // this.iconModelInput = ''
            this.queryObjectQuestionList();
        },

        refreshObjQuesList() {
            this.selectQuestions = [];
            (this.objective = {
                page: 1,
                pageSize: this.objective.pageSize,
                visibility: '',
                typeCode: [],
                modeCode: '',
                difficulty: '',
                visibility: '',
                questionname: ''
            }),
                (this.creatByMeModal = false);
            this.queryObjectQuestionList();
        },
        queryObjectQuestionList() {
            //查询列表
            this.showDataList = false;
            this.showDefImg = true;
            let _this = this;
            let query = {
                pageIndex: _this.objective.page || 1,
                pageSize: _this.objective.pageSize || 20
            };
            let obj = {
                visibility: _this.objective.visibility || ''
            };
            if (_this.objective.questionname) {
                obj.description = this.html2Escape(_this.objective.questionname);
            }
            if (_this.objective.typeCode) {
                obj.typeCode = _this.objective.typeCode; //.join(',')
            }
            if (_this.objective.modeCode) {
                obj.modeCode = _this.objective.modeCode;
            }
            if (_this.objective.difficulty) {
                obj.difficulty = _this.objective.difficulty;
            }
            if (this.creatByMeModal) {
                obj.creator = _this.USER_ID;
                obj.self = 1;
            } else {
                obj.creator = '';
                obj.self = 0;
            }
            queryObjectiveList(obj, query).then((data) => {
                if (data.code === 1) {
                    if (data.data.items && data.data.items.length > 0) {
                        // _this.objectiveList = data.data.items;
                        let items = data.data.items;
                        _this.objectiveList = items;
                        if (items.length > 0) {
                            this.showDataList = true;
                            this.showDefImg = false;
                        } else {
                            this.showDataList = false;
                            this.showDefImg = true;
                        }
                        this.objectiveList.forEach((question) => {
                            if (
                                this.selectQuestions
                                    .map((question) => question.id)
                                    .includes(question.id)
                            ) {
                                this.$set(question, '_checked', true);
                            } else {
                                this.$set(question, '_checked', false);
                            }
                        });
                        if (
                            this.objectiveList.length > 0 &&
                            this.objectiveList.every((question) =>
                                this.selectQuestions
                                    .map((question) => question.id)
                                    .includes(question.id)
                            )
                        ) {
                            this.selectAllQuestion = true;
                        } else {
                            this.selectAllQuestion = false;
                        }
                    } else {
                        this.showDataList = false;
                        this.showDefImg = true;
                        _this.objectiveList = [];
                    }
                    _this.objectListTotal = data.data.total;
                } else {
                    this.showDataList = false;
                    this.showDefImg = true;
                }
                this.loading = false;
            });
        },
        getData(page, size) {
            this.loading = true;
            this.objective.page = page;
            this.objective.pageSize = size;
            this.queryObjectQuestionList();
        },
        changePage(val) {
            this.objective.page = val;
            this.queryObjectQuestionList();
        },
        changeSize(val) {
            this.objective.pageSize = val;
            this.queryObjectQuestionList();
        },
        deleteQuestion(id) {
            let _this = this;
            delQuestion(id).then((data) => {
                if (data.code === 1) {
                    _this.$Message.info('删除成功');
                    _this.queryObjectQuestionList();
                } else {
                    _this.$Message.error(data.message);
                }
            });
        },
        escape2Html(str, needReplace) {
            if (!str) {
                return;
            }
            let repStr = str.replace(/\{\{.*?\}\}/g, '___');
            let arrEntities = {
                lt: '<',
                gt: '>',
                nbsp: ' ',
                amp: '&',
                quot: '"'
            };
            if (needReplace) {
                repStr = repStr.replace(/&(lt|gt|amp|quot|nbsp);/gi, function(all, t) {
                    return arrEntities[t];
                });
            }
            return repStr;
        },
        html2Escape(str) {
            //过滤内容
            let arrEntities = {
                '<': '&lt',
                '>': '&gt',
                ' ': '&nbsp',
                '&': '&amp',
                '"': '&quot'
            };
            return str
                .replace(/\&/g, '&amp;')
                .replace(/\</g, '&lt;')
                .replace(/\>/g, '&gt;')
                .replace(/\ /g, '&nbsp;'); //.replace(/\"/g, "&quot;");
            //return str.replace(/&(\<|\>|\ |\&|\");/ig,function(all,t){return arrEntities[t];});
        },
        addObjectiveQuestion(obj, type) {
            //点击创建或者编辑按钮的回调
            let _this = this;
            _this.preQuestion = false;
            _this.preTxt = '预览';
            _this.disbledAdd = false;
            _this.disAddBlank = false;
            _this.errorTip4 = '';
            _this.questiontypeDisbaled = false;
            _this.addObjectiveQuestionModal.show = true;
            _this.resetField('objectiveQuestionformValidate');
            if (type === 'add') {
                _this.addObjectiveQuestionModal.title = '创建客观题';
                _this.initFormData();
                _this.index = 1;
            } else {
                _this.addObjectiveQuestionModal.title = `编辑客观题`;
                _this.questiontypeDisbaled = true;
                getQuestionAndAnswer(obj.id).then((data) => {
                    if (data.code === 1) {
                        obj.difficulty = obj.difficulty.toLowerCase();
                        Object.assign(_this.objectiveQuestionformValidate, obj, {
                            typeCode: obj.typeCode.toString()
                        }); //obj.typeCode.split(',')
                        _this.objectiveQuestionformValidate.answers = data.data.answers;
                        _this.objectiveQuestionformValidate.answers.sort(function(a, b) {
                            return a.no > b.no ? 1 : -1;
                        });
                        if (_this.objectiveQuestionformValidate.modeCode != 4) {
                            _this.objectiveQuestionformValidate.answers = data.data.answers.map(
                                (item) => {
                                    if (
                                        item.description.indexOf('】') == 2 ||
                                        item.description.indexOf(']') == 2
                                    ) {
                                        item.description = this.escape2Html(
                                            item.description.slice(3),
                                            true
                                        );
                                    }
                                    item.status = 1;
                                    return item;
                                }
                            );
                            _this.objectiveQuestionformValidate.description = _this.escape2Html(
                                _this.objectiveQuestionformValidate.description,
                                true
                            );
                            _this.objectiveQuestionformValidate.explanation = _this.escape2Html(
                                _this.objectiveQuestionformValidate.explanation,
                                true
                            );
                        } else {
                            _this.objectiveQuestionformValidate.answers = data.data.answers.map(
                                (item) => {
                                    item.status = 1;
                                    return item;
                                }
                            );
                            _this.objectiveQuestionformValidate.explanation = _this.escape2Html(
                                _this.objectiveQuestionformValidate.explanation,
                                true
                            );
                            setTimeout(() => {
                                let contentEle = document.getElementById('quesContent');
                                let description = obj.description;
                                let answer1 = 1;
                                description = description.replace(
                                    /\{\{.*?\}\}/g,
                                    `<input class='quesBlank' disabled style='width:40px;padding:0px 5px;outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200)'>`
                                );
                                //								description = description.replace(/\{\{/g,`<input class='quesBlank' style='outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200)'>{{`).replace(/\}\}/g,`}}</input>`);
                                contentEle.innerHTML = description;
                                contentEle = document.getElementById('quesContent');
                                let answersEle = contentEle.getElementsByClassName('quesBlank');
                                for (let index in answersEle) {
                                    let ele = answersEle[index];
                                    if (ele && ele.className == 'quesBlank') {
                                        ele.value = _this.escape2Html(
                                            _this.objectiveQuestionformValidate.answers[
                                                Number(index)
                                            ].explanation,
                                            true
                                        );
                                    }
                                }
                                this.changeContent();
                            });
                        }
                    }
                });
            }
        },
        Trim(str, is_global) {
            var result;
            result = str.replace(/(^\s+)|(\s+$)/g, '');
            if (is_global && is_global.toLowerCase() == 'g') {
                result = result.replace(/\s/g, '');
            }
            return result;
        },
        saveObjectQuestion(name) {
            let _this = this;
            let obj = {};
            let contentEle = document.getElementById('quesContent');
            _this.$refs[name].validate((valid) => {
                if (valid) {
                    if (_this.objectiveQuestionformValidate.modeCode == 4) {
                        this.validAnswer('blur');
                        if (this.errorTip4) {
                            _this.cancelLoading('addObjectiveQuestionModal');
                            return;
                        }
                        Object.assign(
                            obj,
                            _this.initQuestionObj,
                            _this.objectiveQuestionformValidate
                        );
                        let cloneNode = contentEle.cloneNode(true);
                        let answersEle = cloneNode.getElementsByClassName('quesBlank');
                        let answers = Array.from(answersEle).map((ele, index) => {
                            let answer = {
                                answerId: obj.id ? obj.answers[index].answerId : '',
                                description: '',
                                enabled: 1,
                                explanation: this.html2Escape(this.Trim(ele.value)),
                                isRight: 1,
                                no: index + 1,
                                userAnswer: '',
                                questionId: obj.id
                            };
                            answersEle[index].innerHTML = '{{answer' + (index + 1) + '}}';
                            return answer;
                        });
                        obj.answers = answers;
                        obj.description = this.html2Escape(this.Trim(cloneNode.innerText, ':g'));
                        obj.explanation = this.html2Escape(obj.explanation);
                    } else {
                        Object.assign(
                            obj,
                            _this.initQuestionObj,
                            _this.objectiveQuestionformValidate
                        );
                        if (obj.answers.every((answer) => !answer.isRight) && obj.modeCode == '1') {
                            this.$Message.error('请选择1个正确答案!');
                            _this.cancelLoading('addObjectiveQuestionModal');
                            return;
                        } else if (
                            obj.answers.filter((answer) => answer.isRight).length < 2 &&
                            obj.modeCode == '2'
                        ) {
                            this.$Message.error('请至少选择2个正确答案!');
                            _this.cancelLoading('addObjectiveQuestionModal');
                            return;
                        }
                        //obj.typeCode = [obj.typeCode;//obj.typeCode.join(',');
                        obj.description = obj.description;
                        obj.explanation = this.html2Escape(obj.explanation);
                        if (obj.modeCode === 1 || obj.modeCode === 2) {
                            obj.answers.forEach((answer, index) => {
                                answer.no = index + 1;
                                answer.description = this.html2Escape(answer.description);
                            });
                        } else if (obj.modeCode === 3) {
                            obj.answers = obj.answers.slice(0, 1);
                            obj.answers[0].description = '';
                        } else if (obj.modeCode === 5) {
                            obj.answers = obj.answers.slice(0, 1);
                            obj.answers[0].isRight = 1;
                        }
                    }
                    obj.typeCode = obj.typeCode.join(',');
                    if (_this.addObjectiveQuestionModal.title === '创建客观题') {
                        createQuestion(obj).then((data) => {
                            if (data.code === 1) {
                                _this.$Message.info('增加题目成功！');
                                //_this.queryObjectQuestionList();
                                // _this.refreshObjQuesList();
                                _this.addObjectiveQuestionModal.show = false;
                                if (contentEle) {
                                    contentEle.innerHTML = '';
                                }
                                this.$emit('on-success');
                            } else {
                                _this.$Message.error(data.message);
                                _this.cancelLoading('addObjectiveQuestionModal');
                                _this.objectiveQuestionformValidate.answers.forEach(
                                    (item) => (item.description = item.description.slice(3))
                                ); //返回错误信息的时候保持选项内容的格式
                            }
                        });
                    } else {
                        modifyQuestion(obj, obj.id).then((data) => {
                            if (data.code === 1) {
                                _this.$Message.info('编辑题目成功！');
                                // _this.queryObjectQuestionList();
                                _this.addObjectiveQuestionModal.show = false;
                                this.$emit('on-success');
                            } else {
                                _this.cancelLoading('addObjectiveQuestionModal');
                                _this.$Message.error(data.message);
                                _this.objectiveQuestionformValidate.answers.forEach(
                                    (item) => (item.description = item.description.slice(3))
                                ); //返回错误信息的时候保持选项内容的格式
                            }
                        });
                    }
                } else {
                    if (_this.objectiveQuestionformValidate.modeCode == 4) {
                        _this.validAnswer('blur');
                    }
                    _this.cancelLoading('addObjectiveQuestionModal');
                    _this.$Message.error('表单输入有误，请仔细检查是否有必填项没有输入!');
                }
            });
        },
        cancelLoading(name) {
            this[name].loading = false;
            setTimeout(() => {
                this[name].loading = true;
            });
        },
        resetField(name) {
            this.$refs[name].resetFields();
        },
        addAnswers() {
            this.index++;
            this.objectiveQuestionformValidate.answers.push({
                description: '',
                explanation: '',
                index: this.index,
                status: 1,
                isRight: 0,
                answerId: '',
                no: 0,
                enabled: 1,
                questionId: this.objectiveQuestionformValidate.id || ''
            });
        },
        handleRemove(index) {
            this.objectiveQuestionformValidate.answers[index].status = 0;
            this.objectiveQuestionformValidate.answers.splice(index, 1);
            this.index--;
            this.objectiveQuestionformValidate.answers.forEach((item, index) => {
                item.index = index + 1;
            });
        },
        removeFormErrorTip(filed) {
            this.$refs['objectiveQuestionformValidate'].fields.forEach(function(e) {
                if (e.prop == filed) {
                    //这个条件限制可以去掉就是全部重置了
                    e.resetField();
                }
            });
        },
        changeAnswerTxt(val) {
            if (val == 4) {
                this.removeFormErrorTip('description');
                this.objectiveQuestionformValidate.description = '';
            }
            this.preQuestion = false;
            this.preTxt = '预览';
            this.disbledAdd = false;
            this.objectiveQuestionformValidate.answers = [
                {
                    index: 1,
                    answerId: '',
                    description: '',
                    enabled: 1,
                    explanation: '',
                    isRight: 0,
                    no: 1,
                    questionId: '',
                    status: 1
                },
                {
                    index: 2,
                    answerId: '',
                    description: '',
                    enabled: 1,
                    explanation: '',
                    isRight: 0,
                    no: 2,
                    questionId: '',
                    status: 1
                },
                {
                    index: 3,
                    answerId: '',
                    description: '',
                    enabled: 1,
                    explanation: '',
                    isRight: 0,
                    no: 3,
                    questionId: '',
                    status: 1
                },
                {
                    index: 4,
                    answerId: '',
                    description: '',
                    enabled: 1,
                    explanation: '',
                    isRight: 0,
                    no: 4,
                    questionId: '',
                    status: 1
                }
            ];
            // if(val===3){
            //   this.preQuestion = false;
            // }
        },
        singleAnswer(val) {
            this.objectiveQuestionformValidate.answers.forEach((item) => {
                item.isRight = 0;
            });
            this.objectiveQuestionformValidate.answers[val].isRight = 1;
        },
        showQuestion() {
            if (!this.objectiveQuestionformValidate.description) {
                this.$Message.info('请输入题目名称');
                return false;
            }
            if (this.objectiveQuestionformValidate.modeCode != 3) {
                if (
                    this.objectiveQuestionformValidate.answers.every(
                        (item) => item.isRight == '' || item.isRight == 0
                    )
                ) {
                    this.$Message.info('请输入正确选项');
                    return false;
                }
            }
            if (this.preQuestion) {
                this.preTxt = '预览';
                this.disbledAdd = false;
            } else {
                this.preTxt = '返回';
                this.disbledAdd = true;
            }
            this.preQuestion = !this.preQuestion;
        },
        preQuestionFn(obj) {
            //点击题目获取详细信息的回调
            // let params = {
            // 	chaId: obj.id,
            // 	type: obj.modeCode == 4 ? 5 : obj.modeCode
            // }
            getQuestionAndAnswer(obj.id)
                .then((data) => {
                    if (data.code === 1) {
                        this.preQuestionModal = true;
                        data.data.answers.forEach((answer) => {
                            if (
                                answer.description.indexOf('】') == 2 ||
                                answer.description.indexOf(']') == 2
                            ) {
                                answer.description = answer.description.slice(3);
                            }
                        });
                        data.data.answers.sort(function(a, b) {
                            //修正返回数据的顺序,点击详情正常展示
                            return a.no > b.no ? 1 : -1;
                        });
                        this.preQuestionDataObj = data.data;
                        //this.sortQuestionAnswer(this.preQuestionDataObj.answers);
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        // 按钮点击状态
        setReBtnStatus(params) {
            let userid = params.creator;
            if (userid === this.USER_ID || this.isRootDesinger) {
                return false;
            } else {
                return true;
            }
        },
        // 计算index
        handleProIndex(key) {
            return (this.objective.page - 1) * this.objective.pageSize + key + 1;
        },
        pointFilter(code, obj) {
            if (code && obj && obj.length > 0) {
                if (code.includes(',')) {
                    code = code.split(',');
                    return code
                        .map((codes) => {
                            if (obj.filter((items) => items.dictid === codes).length > 0) {
                                return obj.filter((items) => items.dictid === codes)[0].dictname;
                            } else {
                                return '';
                            }
                        })
                        .join(',');
                } else {
                    return obj.filter((item) => item.dictid === code)[0].dictname || '暂无';
                }
            }
        },
        difficultyFilter: (val) => {
            let difficultyStr = '';
            if (val) {
                val = val.toLowerCase();
            }
            switch (val) {
                case 'simple':
                    difficultyStr = '简单';
                    break;
                case 'commonly':
                    difficultyStr = '一般';
                    break;
                case 'medium':
                    difficultyStr = '中等';
                    break;
                case 'hard':
                    difficultyStr = '较难';
                    break;
            }
            return difficultyStr;
        },
        questionMode(type) {
            //1--单选  2--多选 3---判断
            let status = '';
            switch (type) {
                case 1:
                    status = '单选';
                    break;
                case 2:
                    status = '多选';
                    break;
                case 3:
                    status = '判断';
                    break;
                case 4:
                    status = '填空';
                    break;
                case 5:
                    status = '简答';
                    break;
                default:
                    status = '暂无';
                    break;
            }
            return status;
        },
        // 设置可见范围
        setVisibility(val) {
            let obj = {};
            let text = '';
            let color = '';
            if (val === 'share') {
                text = '单位';
                color = '#32CD32';
            } else if (val === 'private') {
                text = '个人';
                color = '#FFA1000';
            } else if (val === 'public') {
                text = '系统';
                color = '#4169E1';
            }
            obj.text = text;
            obj.color = color;
            return obj;
        },
        // 设置知否可点击
        setIsClick(item) {
            if (
                item.visibility === 'public' ||
                (item.creator !== this.USER_ID && !this.isRootDesinger)
            ) {
                return {
                    'pointer-events': 'none'
                };
            }
        },
        // setImgSrc(item) {
        //     if (
        //         item.visibility === 'public' ||
        //         (item.creator !== this.USER_ID && !this.isRootDesinger)
        //     ) {
        //         return require('../../../assets/project/modifys.png');
        //     } else {
        //         return require('../../../assets/project/modifys-h.png');
        //     }
        // },
        // setDelImgSrc(item) {
        //     if (
        //         item.visibility === 'public' ||
        //         (item.creator !== this.USER_ID && !this.isRootDesinger)
        //     ) {
        //         return require('../../../assets/project/delNote-d.png');
        //     } else {
        //         return require('../../../assets/project/delNote-h.png');
        //     }
        // },
        insertBlankSpace() {
            var sel, range;
            var textContent;
            sel = window.getSelection();
            range = sel.getRangeAt(0);
            range.deleteContents();
            //				this.getCaretPosition();
        },
        changeContent(e) {
            //输入框长度对文本变化
            let contentEle = document.getElementById('quesContent');
            let answersEle = contentEle.getElementsByClassName('quesBlank');
            if (answersEle.length > 0) {
                this.disAddBlank = true;
            } else {
                this.disAddBlank = false;
            }
            Array.from(answersEle).forEach((ele, index) => {
                let text_length = 0;
                let str = ele.value;
                for (let i = 0; i < str.length; i++) {
                    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
                        text_length += 2;
                    } else {
                        text_length++;
                    }
                }
                let current_width = Math.ceil(text_length * 7.5) + 10;
                ele.style.width =
                    current_width < 40 ? 40 : current_width > 400 ? 400 : current_width + 'px';
            });
            this.validAnswer('blur');
            //判断内容长度大于1-小于128
            //				if(contentEle.innerText.length){
            this.objectiveQuestionformValidate.description = contentEle.innerText;
            //				}
        },
        getIndexAndCurContent(e) {
            console.log(e);
            e.preventDefault();
            let _this = this;
            if (!(e.clipboardData && e.clipboardData.items)) {
                return;
            }
            for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
                var item = e.clipboardData.items[i];

                if (item.kind === 'string' && item.type === 'text/plain') {
                    item.getAsString(function(str) {
                        _this.insertHtmlAtCaret(_this.html2Escape(str));
                    });
                } else if (item.kind === 'file') {
                    this.$Message.warning('仅允许粘贴文本内容');
                }
            }
            return false;
        },
        validAnswer(type) {
            //校验填空区域
            if (type != 'blur') {
                return;
            }
            this.errorTip4 = '';
            let contentEle = document.getElementById('quesContent');
            let answersEle = contentEle.getElementsByClassName('quesBlank');
            if (!this.Trim(contentEle.innerText, ':g')) {
                this.errorTip4 = '题目名称不能为空';
                return;
            }
            if (answersEle.length == 0) {
                this.errorTip4 = '请插入填空区';
                return;
            }
            if (Array.from(answersEle).some((ele) => !this.Trim(ele.value, ':g'))) {
                this.errorTip4 = '填空区内容不能为空';
                return;
            }
            if (Array.from(answersEle).some((ele) => this.Trim(ele.value).length > 64)) {
                this.errorTip4 = '填空区内容不能超过64个字符';
                return;
            }
            if (contentEle.innerText.length > 1000 || contentEle.innerText.length < 1) {
                this.errorTip4 = '题目名称长度为1-1000个字符';
            }
        },
        //在复杂公式的div contenteditable=true的位置获取焦点并插入内容
        insertHtmlAtCaret(content) {
            let sel, range, textContent;
            sel = window.getSelection();
            if (
                !content &&
                sel.focusNode.id != 'quesContent' &&
                sel.focusNode.parentElement.id != 'quesContent'
            ) {
                return;
            }
            range = sel.getRangeAt(0);
            range.deleteContents();
            if (window.getSelection) {
                // IE9 and non-IE
                if (sel.getRangeAt && sel.rangeCount) {
                    let el = document.createElement('div');
                    if (content) {
                        el.innerHTML = content;
                    } else {
                        el.innerHTML = `<input class='quesBlank' maxlength="64" style='width:40px;padding:0px 5px;box-shadow:none;outline:none;border:none;border-bottom:1px solid rgb(168,166,200)'></input>`;
                    }
                    let frag = document.createDocumentFragment(),
                        node,
                        lastNode;
                    while ((node = el.firstChild)) {
                        lastNode = frag.appendChild(node);
                    }
                    range.insertNode(frag); // Preserve the selection
                    if (lastNode) {
                        range = range.cloneRange();
                        range.setStartAfter(lastNode);
                        range.collapse(true);
                        sel.removeAllRanges();
                        sel.addRange(range);
                    }
                }
            } else if (document.selection && document.selection.type != 'Control') {
                // IE < 9
                document.selection.createRange().pasteHTML(html);
            }
            textContent = document.getElementById('quesContent').innerHTML; //这个也很重要。因为如果不写可能就会覆盖了原来内容替换成你创建的。或者是干脆不显示了。textContent是全局变量是你输入的内容。
            let contentEle = document.getElementById('quesContent');
            let answersEle = contentEle.getElementsByClassName('quesBlank');
            if (answersEle.length > 0) {
                this.disAddBlank = true;
            } else {
                this.disAddBlank = false;
            }
        },
        parseDescription(question) {
            if (!question.answers) {
                return;
            }
            let description;
            description = question.description.replace(
                /\{\{.*?\}\}/g,
                `<span class='quesBlank' disabled style='width:40px;padding:0px 5px;outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200);color:#2d8cf0'></span>`
            );
            let el = document.createElement('div');
            el.innerHTML = description;
            let answersEle = el.getElementsByClassName('quesBlank');
            Array.from(answersEle).forEach((ele, index) => {
                answersEle[index].innerHTML = question.answers[index].explanation;
            });
            return el.innerHTML;
        },
        //导入导出
        //导入客观题
        handleFormatError() {
            this.uploadList = [];
            this.$Message.warning('文件格式错误');
        },
        handleBeforeUpload() {
            this.uploadList = this.$refs.upload.fileList;
            return true;
        },
        handleProgress(event, file, fileList) {},
        getImageUrl(data) {
            this.uploadList = [];
            if (data.code == 0) {
                this.$Message.error(data.message);
            } else {
                let failData = data.data.fail || [];
                let successData = data.data.success || [];
                this.importResultData = {
                    failData,
                    successData
                };
                let allData = [...failData, ...successData];
                if (allData.length > 0) {
                    this.showFailModal = true;
                }
                this.$Message.info('导入客观题完成');
                this.refreshObjQuesList();
            }
        },
        uploadError() {
            this.uploadList = [];
            this.$Message.error('导入客观题失败');
        }
    },
    mounted() {},
    watch: {},
    created() {}
};
</script>
<style scoped>
#quesContent {
  outline: none;
  /* border: 1px solid #1563C2 ; */
  border: 1px solid var(--select-border-color);
  font-size: 14px;
  padding-left: 8px;
  min-height: 60px;
  border-radius: 4px;
  padding-bottom: 10px;
  word-break: break-all;
  height: auto !important;
  border: 1px solid var(--select-border-color);
}

#quesContent span {
  text-decoration: underline;
  display: inline-block;
  min-width: 40px;
}

.quesBlank {
  text-decoration: underline;
  display: inline-block;
  min-width: 40px;
}

.questionclass {
  display: inline-block;
  width: calc(100% - 120px);
  margin-left: 120px;
  margin-bottom: 16px;
}

.downloadUrl {
  color: #fff;
}
.downloadUrl:hover {
  color: #fff;
}
</style>
